<?php
namespace App\Baqi\Alimns;

use AliyunMNS\Client;
use AliyunMNS\Topic;
use AliyunMNS\Constants;
use AliyunMNS\Model\MailAttributes;
use AliyunMNS\Model\SmsAttributes;
use AliyunMNS\Model\BatchSmsAttributes;
use AliyunMNS\Model\MessageAttributes;
use AliyunMNS\Exception\MnsException;
use AliyunMNS\Requests\PublishMessageRequest;

require_once('AliyunMNS/mns-autoloader.php');

class  AliMnsMsg{
    
    private $endPoint  = 'https://1946878843750095.mns.cn-hangzhou.aliyuncs.com';
    private $accessId  = 'LTAIhvedod536Qxc';
    private $accessKey = 'MgEpZQP8IL283GojyRE0UFmwmdP7ef';
    private $topicName = 'Verification'; //主题名字
    private $SignName  = '万店联盟';// 3.1 设置发送短信的签名（SMSSignName）
    private $smsTpl    = [//设置发送短信模板（SMSTemplateCode）
                            'reg'    => 'SMS_47065016',
                            'update' => 'SMS_47105001',
                            'bind'   => 'SMS_47065016',
                            'find'   => 'SMS_47105001',
                            'login'  => 'SMS_47105001',
                            'update_pay'  => 'SMS_47105001',
            ];


    public function __construct()
    {
        /**
         * Step 1. 初始化Client
         */
        $this->client = new Client($this->endPoint, $this->accessId, $this->accessKey);


    }

    //手机号和验证码必须是string
    public function send_sms($mobile, $code, $type = 'reg')
    {
        /**
         * Step 2. 获取主题引用
         */
        $topic = $this->client->getTopicRef($this->topicName);
        /**
         * Step 3. 生成SMS消息属性
         */
        // 3.1 设置发送短信的签名（SMSSignName）和模板（SMSTemplateCode）
        $batchSmsAttributes = new BatchSmsAttributes($this->SignName, $this->smsTpl[$type]);
        // 3.2 （如果在短信模板中定义了参数）指定短信模板中对应参数的值
        $batchSmsAttributes->addReceiver($mobile, array("code" => $code));
        
        $messageAttributes = new MessageAttributes(array($batchSmsAttributes));

        /**
         * Step 4. 设置SMS消息体（必须）
         *
         * 注：目前暂时不支持消息内容为空，需要指定消息内容，不为空即可。
         */
         $messageBody = "smsmessage";
        /**
         * Step 5. 发布SMS消息
         */
        $request = new PublishMessageRequest($messageBody, $messageAttributes);

        try{
            
            $res = $topic->publishMessage($request);
    
            return $res->isSucceed();

        }
        catch (MnsException $e)
        {
            return $e;

        }
    }
}